package com.kaiyufound.asset.allocation.common.util;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author: lihua
 * @Date: 2023-11-16 13:56
 * @description:
 **/
public class CollTool {

    /**
     * 根据属性去重
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T, U extends Comparable<? super U>> List<T> removeDuplicateByKey(List<T> list, Function<? super T, ? extends U> keyExtractor) {
        List<T> resultList = list.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(keyExtractor)
                        )), ArrayList::new)
        );
        return resultList;
    }

    /**
     * 根据某个属性去重
     * 原理就是判断一个元素能否加入到 Set中去
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 根据某个属性去重
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    private static <T> Predicate<T> distinctByKeyTwo(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}
